package com.threeti.mecool.mobile.controller;

import com.threeti.mecool.core.application.acl.PermissionRoleAchievementService;
import com.threeti.mecool.core.application.plan.PlanService;
import com.threeti.mecool.core.application.project.ProjectService;
import com.threeti.mecool.core.domain.model.acl.PermissionRoleAchievement;
import com.threeti.mecool.core.domain.model.acl.User;
import com.threeti.mecool.core.domain.model.dto.AssignableProjectStoreDto;
import com.threeti.mecool.core.domain.model.dto.AssignableProjectStoreWithSellingUploadStatusDto;
import com.threeti.mecool.core.domain.model.plan.PlanJobResult;
import com.threeti.mecool.core.domain.model.plan.PlanResult;
import com.threeti.mecool.core.domain.model.plan.UserStepResult;
import com.threeti.mecool.core.domain.model.plan.pojo.*;
import com.threeti.mecool.core.domain.model.project.Project;
import com.threeti.mecool.core.domain.model.project.ProjectSellingUpload;
import com.threeti.mecool.core.domain.model.project.ProjectStore;
import com.threeti.mecool.core.domain.model.project.SellingUpload;
import com.threeti.mecool.core.infrastructure.persistence.acl.UserRepository;
import com.threeti.mecool.core.infrastructure.persistence.plan.PlanJobResultRepository;
import com.threeti.mecool.core.infrastructure.persistence.plan.PlanResultRepository;
import com.threeti.mecool.core.infrastructure.persistence.project.ProjectSellingUploadRepository;
import com.threeti.mecool.core.infrastructure.persistence.project.ProjectStoreRepository;
import com.threeti.mecool.core.util.ExceptionHelper;
import com.threeti.mecool.mobile.Commander;
import com.threeti.mecool.mobile.interfaces.ResponserDto;
import com.threeti.mecool.mobile.interfaces.dto.ProjectStoreDto;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/plan")
public class PlanMobiController {
    Logger logger = LoggerFactory.getLogger(PlanMobiController.class);
    @Autowired private UserMobiController userController;
    @Autowired private ProjectService projectService;
    @Autowired private UserRepository userRepo;
    @Autowired private PermissionRoleAchievementService permissionRoleAchievementService;
    @Autowired private PlanService planService;
    @Autowired private PlanResultRepository planResultRepository;
    @Autowired private PlanJobResultRepository planJobResultRepository;
    @Autowired private ProjectSellingUploadRepository projectSellingUploadRepository;
    @Autowired private SellingUpload sellingUpload;
    @Autowired private ProjectStoreRepository projectStoreRepository;

    @RequestMapping("/find")
    @ResponseBody
    public ResponserDto getPlan(@RequestParam("date") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date date,
                                @RequestParam("userLoginName") String userLoginName) {
        ResponserDto ret = ResponserDto.successCommand(Commander.command());
        Date planDate = new DateTime(date).toDate();
        List<Plan> planList = new ArrayList<Plan>(2);
        Plan dailyPlan = Plan.findUserDailyPlan(userLoginName, planDate);
        if (dailyPlan != null && !Plan.STATUS_NEW.equals(dailyPlan.getStatus()) && !Plan.STATUS_DENY.equals(dailyPlan.getStatus())) {
            planList.add(dailyPlan);
        }
        Plan assignedPlan = Plan.findUserAssignedPlan(userLoginName, planDate);
        if (assignedPlan != null && !Plan.STATUS_NEW.equals(assignedPlan.getStatus()) && !Plan.STATUS_DENY.equals(assignedPlan.getStatus())) {
            planList.add(assignedPlan);
        }
        mergePlanProject(planList);
        removeFinishedJob(planList);
        ret.withBizSuccessBody("plans", planList);
        return ret;
    }

    private void mergePlanProject(List<Plan> plans) {
        for (Plan plan : plans) {
            Map<String, PlanProject> mergedPlanProjects = new HashMap<String, PlanProject>();
            Set<PlanProject> removedPlanProjects = new HashSet<PlanProject>();
            for (PlanProject planProject : plan.getPlanProjects()) {
                if (!mergedPlanProjects.containsKey(planProject.getProjectCode())) {
                    mergedPlanProjects.put(planProject.getProjectCode(), planProject);
                } else {
                    removedPlanProjects.add(planProject);
                }
            }
            for (PlanProject removedPlanProject : removedPlanProjects) {
                PlanProject mergedPlanProject = mergedPlanProjects.get(removedPlanProject.getProjectCode());
                for (PlanJob planJob : removedPlanProject.getPlanJobs()) {
                    mergedPlanProject.addPlanJob(planJob);
                }
                plan.getPlanProjects().remove(removedPlanProject);
            }
        }
    }

    private void removeFinishedJob(List<Plan> plans) {
        Iterator<Plan> planIterator = plans.iterator();
        while (planIterator.hasNext()) {
            Plan plan = planIterator.next();
            Iterator<PlanProject> planProjectIterator = plan.getPlanProjects().iterator();
            while (planProjectIterator.hasNext()) {
                PlanProject planProject = planProjectIterator.next();
                Iterator<PlanJob> planJobIterator = planProject.getPlanJobs().iterator();
                while (planJobIterator.hasNext()) {
                    PlanJob planJob = planJobIterator.next();
                    PlanJobResult planJobResult = planJobResultRepository.findByPlanJob_IdAndFinishedAtIsNotNull(planJob.getId());
                    if (planJobResult != null) {
                        planJobIterator.remove();
                    }
                }
                if (planProject.getPlanJobs().size() == 0) {
                    planProjectIterator.remove();
                }
            }
            if (plan.getPlanProjects().size() == 0) {
                planIterator.remove();
            }
        }
    }

    @RequestMapping("/myplan")
    @ResponseBody
    public ResponserDto getMyPlan(@RequestParam("date") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date date,
                                  @RequestParam("userLoginName") String userLoginName) {
        ResponserDto ret = ResponserDto.successCommand(Commander.command());
        Date planDate = new DateTime(date).toDate();
        Plan dailyPlan = Plan.findUserDailyPlan(userLoginName, planDate);
        if (dailyPlan != null && Plan.STATUS_NEW.equals(dailyPlan.getStatus())) {
            dailyPlan = null;
        }
        ret.withBizSuccessBody("plan", dailyPlan);
        return ret;
    }

    @RequestMapping("/beforemake")
    @ResponseBody
    public ResponserDto beforeMakePlanWithStore(@RequestParam(required = true) String userLoginName) {
        return userController.ownProjectWithStores(userLoginName);
    }

    @RequestMapping("/beforemakewithoutstore")
    @ResponseBody
    public ResponserDto beforeMakePlan(@RequestParam String userLoginName) {
        return userController.ownedProjects(userLoginName);
    }

    @RequestMapping(value = "/uploadstep", method = RequestMethod.POST)
    @ResponseBody
    public ResponserDto saveUserStepResult(@RequestParam("userLoginName") String userLoginName,
                                           @RequestParam("plan_id") Long planId,
                                           @RequestBody MobileStepResult[] mobileStepResults) {
        ResponserDto ret = ResponserDto.successCommand(Commander.command());
        try {
            PlanResult planResult = PlanResult.optByPlanId(planId);
            //<editor-fold desc="remove unfinished job result">
    //        planResult.getPlanJobResults().clear();
            Set<Long> updatedPlanJobIdList = new HashSet<Long>();
            for (MobileStepResult mobileStepResult : mobileStepResults) {
                updatedPlanJobIdList.add(mobileStepResult.planJobId);
            }
            List<PlanJobResult> outdatedJobResultList = new ArrayList<PlanJobResult>(planResult.getPlanJobResults().size());
            Set<Long> outdatedJobResultSet = new HashSet<Long>();
            for (PlanJobResult planJobResult : planResult.getPlanJobResults()) {
                Long planJobId = planJobResult.getPlanJob().getId();
                if (planJobResult.getFinishedAt() == null || updatedPlanJobIdList.contains(planJobId)) {
                    if (!outdatedJobResultSet.contains(planJobId)) {
                        outdatedJobResultList.add(planJobResult);
                        outdatedJobResultSet.add(planJobId);
                    }
                }
            }
            for (int i = outdatedJobResultList.size() - 1; i >= 0; i--) {
                planJobResultRepository.delete(outdatedJobResultList.get(i));
            }
            //</editor-fold>
            for (MobileStepResult mobileStepResult : mobileStepResults) {
                PlanJobResult planJobResult = planResult.optPlanJobResultByPlanJobId(mobileStepResult.planJobId);
                planJobResult.setJobStatus(PlanJobResult.JOB_STATUS_FINISHED);
                Date jobFinishedAt = planJobResult.getFinishedAt();
                if (jobFinishedAt == null || jobFinishedAt.before(mobileStepResult.finishedAt)) {
                    planJobResult.setFinishedAt(mobileStepResult.finishedAt);
                    planJobResult.setJobStartedLongitude(String.valueOf(mobileStepResult.longitude));
                    planJobResult.setJobStartedLatitude(String.valueOf(mobileStepResult.latitude));
                }

                UserStepResult userStepResult = planJobResult.optUserStepResult(mobileStepResult.stepId);
                userStepResult.setData(mobileStepResult.data);
                userStepResult.setDataExtra(mobileStepResult.dataExtra);
                userStepResult.setFinishedAt(mobileStepResult.finishedAt);
                userStepResult.setLatitude(mobileStepResult.latitude);
                userStepResult.setLongitude(mobileStepResult.longitude);
            }
            planResult.save();
            ret.withBizSuccessBody("ok", "1");
            return ret;
        } catch (Exception e) {
            logger.error("upload step", e);
            ResponserDto.withBizFailureMsg(Commander.command(), "ERROR", e.getMessage());
            return ret;
        }
    }

    @RequestMapping(value = "/addplan", method = RequestMethod.POST)
    @ResponseBody
    public ResponserDto addPlan(@RequestBody Plan plan,
                                @RequestParam("key") String key) {
        ResponserDto ret = ResponserDto.successCommand(Commander.command());
        Plan existedPlan = Plan.findUserDailyPlan(plan.getUserLoginName(), plan.getPlanDate());
        if (existedPlan != null) {
            PlanResult planResult = planResultRepository.findByPlan_Id(existedPlan.getId());
            if (planResult != null) {
                planResultRepository.delete(planResult);
            }
            existedPlan.delete();
        }
        plan.clearPersistStatus();
        plan.save();
        ret.withBizSuccessBody("key", key);
        ret.withBizSuccessBody("planId", plan.getId());
        ret.withBizSuccessBody("version", plan.getVersion());
        return ret;
    }

    @RequestMapping("/findjobs")
    @ResponseBody
    public ResponserDto findJobs(@RequestParam("userLoginName") String userLoginName) {
        ResponserDto ret = ResponserDto.successCommand(Commander.command());
        Map<PermissionRoleAchievement, Long> achievementMap = permissionRoleAchievementService.findMonthlyResult(userLoginName, new Date());
        Map<Long, List<Number>> jobAchievementMap = new HashMap<Long, List<Number>>();
        for (Map.Entry<PermissionRoleAchievement, Long> entry : achievementMap.entrySet()) {
            List<Number> list = new ArrayList<Number>(2);
            list.add(entry.getKey().getTargetCount());
            list.add(entry.getValue());
            jobAchievementMap.put(entry.getKey().getJob().getId(), list);
        }
        User user = userRepo.findByloginName(userLoginName);
        Map<Project, List<Job>> projectJobMap = planService.findUserProjectJob(userLoginName);
        List<Object> retList = new ArrayList<Object>();
        for (Map.Entry<Project, List<Job>> entry : projectJobMap.entrySet()) {
            Map<String, Object> map = new HashMap<String, Object>();
            Project project = entry.getKey();
            map.put("projectCode", project.getCode());
            map.put("projectName", project.getName());
            List<Map<String, Object>> jobMapList = new ArrayList<Map<String, Object>>();
            for (Job job : entry.getValue()) {
                Map<String, Object> jobMap = new HashMap<String, Object>();
                jobMap.put("jobId", job.getId());
                jobMap.put("jobName", job.getName());
                jobMap.put("criticalJob", planService.isCriticalJob(project.getCode(), job.getId()));
                List<Number> jobAchievementList = jobAchievementMap.get(job.getId());
                if (jobAchievementList != null) {
                    jobMap.put("requiredCount", jobAchievementList.get(0));
                    jobMap.put("finishedCount", jobAchievementList.get(1));
                } else {
                    jobMap.put("requiredCount", -1);
                    jobMap.put("finishedCount", -1);
                }
                jobMapList.add(jobMap);
            }
            map.put("jobs", jobMapList);
//            List<ProjectStore> projectStoreList = projectService.findStoresPreAssignedToUserWithinTheProject(user, project.getId());
//            List<ProjectStoreDto> projectStoreDtoList = new ArrayList<ProjectStoreDto>();
//            for (ProjectStore projectStore : projectStoreList) {
//                projectStoreDtoList.add(ProjectAssembler.toDto(projectStore));
//            }
//            Collections.sort(projectStoreDtoList, new Comparator<ProjectStoreDto>() {
//                @Override
//                public int compare(ProjectStoreDto o1, ProjectStoreDto o2) {
//                    int val = o1.getCode().compareTo(o2.getCode());
//                    if (val == 0) {
//                        val = o1.getName().compareTo(o2.getName());
//                    }
//                    return val;
//                }
//            });
//            map.put("stores", projectStoreDtoList);
            map.put("stores", new ArrayList<ProjectStoreDto>(0));
            retList.add(map);
        }
        ret.withBizSuccessBody("projects", retList);
        return ret;
    }

    @RequestMapping("/monthlyachievement")
    @ResponseBody
    public ResponserDto findMonthlyAchievement(@RequestParam("userLoginName") String userLoginName) {
        Map<PermissionRoleAchievement, Long> achievementMap = permissionRoleAchievementService.findMonthlyResult(userLoginName, new Date());
        Map<Long, Long> retData = new HashMap<Long, Long>(achievementMap.size(), 1);
        List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>(retData.size());
        for (Map.Entry<PermissionRoleAchievement, Long> achievementEntry : achievementMap.entrySet()) {
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("jobId", achievementEntry.getKey().getJob().getId());
            data.put("requiredCount", achievementEntry.getKey().getTargetCount());
            data.put("finishedCount", achievementEntry.getValue());
        }
        ResponserDto ret = ResponserDto.successCommand(Commander.command());
        ret.withBizSuccessBody("achievements", dataList);
        return ret;
    }

    @RequestMapping("/uploadunfinished")
    @ResponseBody
    public ResponserDto uploadUnfinishedJob(@RequestParam("userLoginName") String userLoginName,
                                            @RequestParam("planId") long planId,
                                            @RequestParam("planJobId") long planJobId,
                                            @RequestParam("notes") String notes) {
        try {
            PlanResult planResult = PlanResult.optByPlanId(planId);
            PlanJobResult planJobResult = planResult.optPlanJobResultByPlanJobId(planJobId);
            planJobResult.setFinishedAt(new Date());
            planJobResult.setNotes(notes);
            planJobResult.setJobStatus(PlanJobResult.JOB_STATUS_NOT_FINISHED);
            planResult.save();
            return ResponserDto.withBizSuccessMsg(Commander.command(), "ok", "1");
        } catch (Exception e) {
            return ResponserDto.withBizFailureMsg(Commander.command(), "ERROR", e.getMessage());
        }
    }

    @RequestMapping("/listplans")
    @ResponseBody
    public ResponserDto listPlansViaDate(@RequestParam("userLoginName") String userLoginName,
                                         @RequestParam("date") @DateTimeFormat(pattern = "yyyy-MM-dd") Date date) {
        ResponserDto ret = ResponserDto.successCommand(Commander.command());
        List<Plan> planList = Plan.findByUserAfterDate(userLoginName, date);
        Collections.sort(planList, new Comparator<Plan>() {
            @Override
            public int compare(Plan plan1, Plan plan2) {
                return plan2.getPlanDate().compareTo(plan1.getPlanDate());
            }
        });
        List<Map<String, Object>> plans = new ArrayList<Map<String, Object>>(planList.size());
        for (Plan plan : planList) {
            Map<String, Object> planDto = new HashMap<String, Object>();
            plans.add(planDto);
            planDto.put("planId", plan.getId());
            planDto.put("name", plan.getName());
            planDto.put("planDate", plan.getPlanDate());
            planDto.put("status", plan.getStatus());
            planDto.put("denyNotes", plan.getDenyNotes());
            planDto.put("changeNotes", plan.getChangeNotes());
        }
        ret.withBizSuccessBody("plans", plans);
        return ret;
    }

    @RequestMapping("/listplanjobs")
    @ResponseBody
    public ResponserDto listPlanJobs(@RequestParam("planId") Long planId) {
        ResponserDto ret = ResponserDto.successCommand(Commander.command());
        Plan plan = Plan.findById(planId);
        List<Map<String, Object>> planJobs = new ArrayList<Map<String, Object>>();
        DateFormat dateFormat = new SimpleDateFormat("HH:mm");
        if (plan != null) {
            for (PlanProject planProject : plan.getPlanProjects()) {
                for (PlanJob planJob : planProject.getPlanJobs()) {
                    Map<String, Object> planJobDto = new HashMap<String, Object>();
                    planJobs.add(planJobDto);
                    planJobDto.put("planId", planId);
                    planJobDto.put("projectCode", planProject.getProjectCode());
                    planJobDto.put("projectName", planProject.getProjectName());
                    planJobDto.put("storeCode", planJob.getStoreCode());
                    planJobDto.put("storeName", planJob.getStoreName());
                    planJobDto.put("jobId", planJob.getJob().getId());
                    planJobDto.put("jobName", planJob.getJob().getName());
                    planJobDto.put("startTime", dateFormat.format(planJob.getStartTime()));
                    planJobDto.put("endTime", dateFormat.format(planJob.getEndTime()));
                }
            }
        }
        ret.withBizSuccessBody("planJobs", planJobs);
        return ret;
    }

    @RequestMapping("/projectstores")
    @ResponseBody
    public ResponserDto listProjectStores(@RequestParam String userLoginName, @RequestParam String projectCode, @RequestParam(required = false) String storeName,
                                          Pageable pageable) {
        storeName = storeName == null ? "" : storeName.trim();
        if (!storeName.isEmpty()) storeName = '%' + storeName + '%';
        Page<AssignableProjectStoreDto> page = projectService.listAssignableProjectStores(userLoginName, projectCode, storeName, pageable);
        ResponserDto data = ResponserDto.successCommand(Commander.command());
        data.withBizSuccessBody("page", page.getNumber() + 1);
        data.withBizSuccessBody("size", page.getSize());
        data.withBizSuccessBody("isLast", page.isLastPage() ? 1 : 0);
        data.withBizSuccessBody("projectCode", projectCode);
        data.withBizSuccessBody("storeName", storeName);
        data.withBizSuccessBody("stores", page.getContent());
        return data;
    }

    @RequestMapping("/projectstoreswithsellupload")
    @ResponseBody
    public ResponserDto listProjectStoresWithSellingUpload(@RequestParam String userLoginName,
                                                           @RequestParam String projectCode,
                                                           @RequestParam(required = false) String storeName,
                                                           @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date date,
                                                           Pageable pageable) {
        try {
            storeName = storeName == null ? "" : storeName.trim();
            if (!storeName.isEmpty()) storeName = '%' + storeName + '%';
            Page<AssignableProjectStoreDto> page = projectService.listAssignableProjectStores(userLoginName, projectCode, storeName, pageable);
            DateTime sellDate = date == null ? sellingUpload.calculateSellDate() : new DateTime(date);
            List<AssignableProjectStoreWithSellingUploadStatusDto> stores = sellingUpload.fillUploadStatus(sellDate.toDate(), page.getContent());
            ResponserDto data = ResponserDto.successCommand(Commander.command());
            ProjectSellingUpload projectSellingUpload = projectSellingUploadRepository.findByProjectCode(projectCode);
            data.withBizSuccessBody("page", page.getNumber() + 1);
            data.withBizSuccessBody("size", page.getSize());
            data.withBizSuccessBody("isLast", page.isLastPage() ? 1 : 0);
            data.withBizSuccessBody("projectCode", projectCode);
            data.withBizSuccessBody("storeName", storeName);
            data.withBizSuccessBody("date", sellDate.toString("yyyy-MM-dd"));
            data.withBizSuccessBody("configUpdatedAt", projectSellingUpload != null ? new SimpleDateFormat("yyyyMMddHHmmss").format(projectSellingUpload.getUpdatedAt()) : "");
            data.withBizSuccessBody("stores", stores);
            return data;
        } catch (Exception e) {
            e = ExceptionHelper.getPreSaveValidateException(e);
            return ResponserDto.withBizFailureMsg(Commander.command(), "ERROR", e.getMessage());
        }
    }

    @RequestMapping("/sellinguploadstoreform")
    @ResponseBody
    public ResponserDto viewSellingUploadStoreForm(@RequestParam String projectCode,
                                                   @RequestParam String storeCode,
                                                   @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date date) {
        try {
            DateTime sellDate = date == null ? sellingUpload.calculateSellDate() : new DateTime(date);
            Map<String, Object> map = new HashMap<String, Object>();
            ProjectStore projectStore = projectStoreRepository.findByProject_CodeAndChannel_Channel_Code(projectCode, storeCode);
            int target = sellingUpload.getSummary(projectStore.getId(), sellDate.getYear(), sellDate.getMonthOfYear());
            double monthSummary = sellingUpload.getMonthSummary(projectStore.getId(), sellDate.getYear(), sellDate.getMonthOfYear(), sellDate);
            String percentage = "";
            if (target != 0) {
                percentage = String.format("%.0f%%", monthSummary / target * 100);
            } else {
                percentage = String.format("%.0f元", monthSummary);
            }
            ProjectSellingUpload projectSellingUpload = projectSellingUploadRepository.findByProject_Id(projectStore.getProject().getId());
            String fields = "";
            boolean storeUploaded = false;
            List<Map<String, Object>> list = new LinkedList<Map<String, Object>>();
            if (projectSellingUpload != null) {
                storeUploaded = sellingUpload.isSellingUploaded(projectStore.getId(), sellDate.toDate());
                boolean withAmount = projectSellingUpload.getUploadAmount() == 1;
                boolean withPrice = projectSellingUpload.getUploadPrice() == 1;
                if (withPrice) fields += "p";
                if (withAmount) fields += "au";
                list = sellingUpload.getUploadList(projectStore, sellDate.toDate());
            }
            map.put("name", projectStore.getChannel().getChannel().getName());
            map.put("date", sellDate.toString("yyyy-M-d"));
            map.put("uploaded", storeUploaded ? 1 : 0);
            map.put("target", target + "元");
            map.put("percent", percentage);
            map.put("fields", fields);
            map.put("list", list);
            return ResponserDto.successCommand(Commander.command()).withBizSuccessBody("store", map);
        } catch (Exception e) {
            e = ExceptionHelper.getPreSaveValidateException(e);
            logger.error(e.getMessage(), e);
            return ResponserDto.withBizFailureMsg(Commander.command(), "ERROR", e.getMessage());
        }
    }

    @RequestMapping(value = "/sellingupload", method = RequestMethod.POST)
    @ResponseBody
    public ResponserDto sellingUpload(@RequestBody Map<String, Object> data) {
        try {
            String loginName = (String) data.get("loginName");
            String projectCode = (String) data.get("projectCode");
            String storeCode = (String) data.get("storeCode");
            Date date = new SimpleDateFormat("yyyy-MM-dd").parse((String) data.get("date"));
            Map<String, Map<String, Number>> uploadData = new HashMap<String, Map<String, Number>>();
            Collection dataList = (Collection) data.get("data");
            for (Object o : dataList) {
                Map m = (Map) o;
                Map<String, Number> uploadItem = new HashMap<String, Number>();
                uploadData.put((String) m.get("c"), uploadItem);
                uploadItem.put("amount", (Number) m.get("a"));
                uploadItem.put("summary", (Number) m.get("s"));
                uploadItem.put("price", (Number) m.get("p"));
            }
            ProjectStore projectStore = projectStoreRepository.findByProject_CodeAndChannel_Channel_Code(projectCode, storeCode);
            if (projectStore == null) {
                throw new RuntimeException("当前项目中未找到对应终端\n请重新刷新项目终端列表");
            }
            sellingUpload.saveUploadValues(loginName, projectStore.getId(), date, uploadData);
            return ResponserDto.withBizSuccessMsg(Commander.command(), "OK", "上报成功");
        } catch (Exception e) {
            Exception pe = ExceptionHelper.getPreSaveValidateException(e, false);
            if (pe == null) {
                logger.error("save selling upload", pe);
            } else {
                e = pe;
            }
            return ResponserDto.withBizFailureMsg(Commander.command(), "ERROR", e.getMessage());
        }
    }
}
